﻿#region Header

/*
    This file is part of nDoctor Light

    NDoctor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    NDoctor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with NDoctor.  If not, see <http://www.gnu.org/licenses/>.
*/

#endregion Header

namespace Probel.Ldoc.Shell.Views
{
    using System;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows;

    using log4net;

    using Probel.Ldoc.Dal.Configuration;
    using Probel.Ldoc.Services.Services;
    using Probel.Ldoc.Shell.Configuration;
    using Probel.Ldoc.Shell.Properties;
    using Probel.Ldoc.Shell.Tools;
    using Probel.Ldoc.ViewModels;

    /// <summary>
    /// Interaction logic for SpashScreen.xaml
    /// </summary>
    public partial class SplashScreenView : Window
    {
        #region Fields

        private readonly AppContext AppContext = AppContext.Instance;
        private readonly ILog Logger = LogManager.GetLogger(typeof(SplashScreen));

        #endregion Fields

        #region Constructors

        public SplashScreenView()
        {
            InitializeComponent();
        }

        #endregion Constructors

        #region Methods

        public void Load()
        {
            this.Logger.Info("Application is starting...");

            this.Logs.Text = Messages.Msg_InitialiseComponents;
            this.Progress.Value = 25;

            var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            Task.Run(() => this.InitialiseComponents())
                .ContinueWith(t =>
                {
                    Logger.Debug("Configuring nHibernate...");
                    this.Logs.Text = Messages.Msg_InitialiseNHibernate;
                    this.Progress.Value = 50;
                }, CancellationToken.None, TaskContinuationOptions.NotOnFaulted, scheduler)
                .ContinueWith(t => this.InitialiseNHibernate())
                .ContinueWith(t =>
                {
                    Logger.Debug("Initialisation is done.");
                    this.Progress.Value = 100;
                    this.Close();
                }, CancellationToken.None, TaskContinuationOptions.NotOnFaulted, scheduler);
        }

        private void InitialiseComponents()
        {
            //An aggregate catalog that combines multiple catalogs
            var cabinet = new AggregateCatalog();

            //Adds all the parts found in the same assembly as the Program class
            cabinet.Catalogs.Add(new AssemblyCatalog(typeof(IDalManager).Assembly));
            cabinet.Catalogs.Add(new AssemblyCatalog(typeof(ViewModelFactory).Assembly));
            cabinet.Catalogs.Add(new AssemblyCatalog(typeof(IErrorService).Assembly));
            cabinet.Catalogs.Add(new AssemblyCatalog(typeof(ErrorService).Assembly));

            //Create the CompositionContainer with the parts in the catalog
            var container = new CompositionContainer(cabinet);

            //Fill the imports of this object
            try
            {
                container.ComposeParts(AppContext);
            }
            catch (CompositionException compositionException)
            {
                //Console.WriteLine(compositionException.ToString());
                Logger.Error("Failed to initialise components", compositionException);
                throw;
            }
        }

        private void InitialiseNHibernate()
        {
            try
            {
                var path = Environment.ExpandEnvironmentVariables(ConfigFile.GetConfiguration().Database);
                Logger.Debug(path);

                this.AppContext.DalConfigurator.ConfigureUsingFile(path);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.ToString());
                Logger.Error("Failed to initialise components", ex);
                throw;
            }
        }

        #endregion Methods
    }
}